<template>
  <div class="pm-worklog-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>项目工时统计</h2>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20" class="filter-row">
        <el-col :span="5">
          <el-form-item label="项目选择" required>
            <el-select v-model="queryParams.projectId" placeholder="请选择项目" style="width: 100%" @change="handleProjectChange">
              <el-option
                v-for="project in projectOptions"
                :key="project.projectId"
                :label="project.projectName"
                :value="project.projectId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="queryParams.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              @change="handleDateRangeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch" :disabled="!queryParams.projectId">搜索</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 项目概览卡片 -->
    <el-row v-if="queryParams.projectId" :gutter="20" class="summary-cards">
      <el-col :span="8">
        <el-card class="summary-card">
          <div class="card-content">
            <div class="card-icon total">
              <i class="el-icon-time"></i>
            </div>
            <div class="card-info">
              <div class="card-title">项目总投入工时</div>
              <div class="card-value">{{ overviewData.totalHours || 0 }}<span class="unit">小时</span></div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="summary-card">
          <div class="card-content">
            <div class="card-icon overtime">
              <i class="el-icon-alarm-clock"></i>
            </div>
            <div class="card-info">
              <div class="card-title">总加班工时</div>
              <div class="card-value">{{ overviewData.overtimeHours || 0 }}<span class="unit">小时</span></div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="summary-card">
          <div class="card-content">
            <div class="card-icon members">
              <i class="el-icon-user"></i>
            </div>
            <div class="card-info">
              <div class="card-title">参与人数</div>
              <div class="card-value">{{ overviewData.memberCount || 0 }}<span class="unit">人</span></div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Tab页切换区域 -->
    <el-card v-if="queryParams.projectId" class="tabs-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="statistics-tabs" :key="tabKey">
        <el-tab-pane label="按成员统计" name="member">
          <el-table
            v-if="activeTab === 'member'"
            v-loading="memberLoading"
            :data="memberStatsList"
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
            :empty-text="memberLoading ? '' : '暂无数据'"
          >
             <el-table-column prop="userName" label="成员姓名" width="120" />
             <el-table-column prop="deptName" label="所属部门" min-width="150" />
             <el-table-column prop="totalHours" label="总工时" width="100" align="center">
               <template #default="scope">
                 <span>{{ scope.row.totalHours || 0 }}h</span>
               </template>
             </el-table-column>
             <el-table-column prop="overtimeHours" label="其中加班工时" width="120" align="center">
               <template #default="scope">
                 <span>{{ scope.row.overtimeHours || 0 }}h</span>
               </template>
             </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="按任务统计" name="task">
          <el-table
            v-if="activeTab === 'task'"
            v-loading="taskLoading"
            :data="taskStatsList"
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
            :empty-text="taskLoading ? '' : '暂无数据'"
          >
            <el-table-column prop="taskId" label="任务ID" width="100" align="center" />
            <el-table-column prop="taskName" label="任务名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="totalHours" label="总投入工时" width="120" align="center">
              <template #default="scope">
                <span>{{ scope.row.totalHours || 0 }}h</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="任务状态" width="100" align="center">
              <template #default="scope">
                <span :class="['status-tag', getStatusColor(scope.row.status)]">
                  {{ getTaskStatusText(scope.row.status) }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

      </el-tabs>
    </el-card>

    <!-- 未选择项目时的提示 -->
    <el-empty v-else description="请选择项目后查看统计数据" :image-size="120" />
  </div>
</template>

<script>
import { 
  getProjectListForPM, 
  getWorklogOverview, 
  getWorklogStatsByMember, 
  getWorklogStatsByTask
} from '@/api/oa/worklog'

export default {
  name: 'PMWorklogView',
  data() {
    return {
      activeTab: 'member',
      tabKey: 0,
      projectOptions: [],
      overviewData: {},
      memberStatsList: [],
      taskStatsList: [],
       memberLoading: false,
       taskLoading: false,
      queryParams: {
        projectId: null,
        dateRange: null,
        params: {}
      }
    }
  },

  created() {
    this.loadProjectOptions()
  },
  methods: {
    // 加载项目选项
    async loadProjectOptions() {
      try {
        const response = await getProjectListForPM()
        if (response.code === 200) {
          this.projectOptions = response.data || []
        }
      } catch (error) {
        console.error('加载项目列表失败:', error)
        this.projectOptions = []
      }
    },

    // 项目变化时加载数据
    async handleProjectChange(projectId) {
      if (projectId) {
        // 立即清空之前的数据并设置loading状态
        this.resetAllData()
        this.setLoadingState(this.activeTab, true)
        
        // 自动加载概览数据和第一个tab的数据
        await this.loadOverviewData()
        await this.loadTabData()
      } else {
        this.resetAllData()
      }
    },

    // 处理日期范围变化
    handleDateRangeChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.queryParams.params.beginTime = dateRange[0]
        this.queryParams.params.endTime = dateRange[1]
      } else {
        this.queryParams.params.beginTime = ''
        this.queryParams.params.endTime = ''
      }
    },

    // 搜索
    handleSearch() {
      if (!this.queryParams.projectId) {
        this.$message.warning('请先选择项目')
        return
      }
      this.loadOverviewData()
      this.loadTabData()
    },


    // 重置
    handleReset() {
      this.queryParams = {
        projectId: null,
        dateRange: null,
        params: {}
      }
      this.resetAllData()
    },

    // Tab切换
    handleTabClick(tab) {
      // 强制重新渲染Tab组件
      this.tabKey++
      // 立即设置loading状态
      this.setLoadingState(tab.name, true)
      // 加载数据
      this.$nextTick(() => {
        this.loadTabData()
      })
    },

     // 清空当前Tab的数据
     clearCurrentTabData(tabName) {
       switch (tabName) {
         case 'member':
           this.memberStatsList = []
           break
         case 'task':
           this.taskStatsList = []
           break
       }
     },

    // 设置对应Tab的loading状态
    setLoadingState(tabName, loading) {
      switch (tabName) {
        case 'member':
          this.memberLoading = loading
          break
        case 'task':
          this.taskLoading = loading
          break
      }
    },

    // 加载概览数据
    async loadOverviewData() {
      if (!this.queryParams.projectId) return
      
      try {
        const params = {
          projectId: this.queryParams.projectId,
          beginTime: this.queryParams.params.beginTime,
          endTime: this.queryParams.params.endTime
        }
        const response = await getWorklogOverview(params)
        if (response.code === 200) {
          this.overviewData = response.data || {}
        }
      } catch (error) {
        console.error('加载概览数据失败:', error)
        this.overviewData = {}
      }
    },

     // 加载Tab数据
     async loadTabData() {
       if (!this.queryParams.projectId) {
         return
       }

       switch (this.activeTab) {
         case 'member':
           this.loadMemberStats()
           break
         case 'task':
           this.loadTaskStats()
           break
       }
     },

     // 加载成员统计
     async loadMemberStats() {
       this.memberLoading = true
       try {
         const params = {
           projectId: this.queryParams.projectId,
           beginTime: this.queryParams.params.beginTime,
           endTime: this.queryParams.params.endTime
         }
         const response = await getWorklogStatsByMember(params)
         if (response.code === 200) {
           // 使用分页数据格式的rows字段
           this.memberStatsList = response.rows || []
         }
       } catch (error) {
         console.error('加载成员统计失败:', error)
         this.memberStatsList = []
       } finally {
         this.memberLoading = false
       }
     },

     // 加载任务统计
     async loadTaskStats() {
       this.taskLoading = true
       try {
         const params = {
           projectId: this.queryParams.projectId,
           beginTime: this.queryParams.params.beginTime,
           endTime: this.queryParams.params.endTime
         }
         const response = await getWorklogStatsByTask(params)
         if (response.code === 200) {
           // 使用分页数据格式的rows字段
           this.taskStatsList = response.rows || []
         }
       } catch (error) {
         console.error('加载任务统计失败:', error)
         this.taskStatsList = []
       } finally {
         this.taskLoading = false
       }
     },


    // 重置所有数据
    resetAllData() {
      this.overviewData = {}
      this.memberStatsList = []
      this.taskStatsList = []
    },

    // 获取进度颜色
    getProgressColor(percentage) {
      if (percentage < 30) return '#f56c6c'
      if (percentage < 70) return '#e6a23c'
      return '#67c23a'
    },

    // 获取状态颜色
    getStatusColor(status) {
      const statusMap = {
        'pending': 'status-orange',
        'archived': 'status-green',
        'rejected': 'status-red',
        'returned': 'status-gray',
        '0': 'status-green',    // 已完成 - 绿色
        '1': 'status-blue',     // 进行中 - 蓝色
        '2': 'status-gray',     // 未完成 - 灰色
        '3': 'status-red'       // 延期 - 红色
      }
      return statusMap[status] || 'status-default'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'pending': '待归档',
        'archived': '已归档',
        'rejected': '已驳回',
        'returned': '已退回'
      }
      return statusMap[status] || status
    },

     // 获取任务状态文本
     getTaskStatusText(status) {
       const statusMap = {
         '0': '已完成',
         '1': '进行中',
         '2': '未完成',
         '3': '延期'
       }
       return statusMap[status] || status
     },

     // 获取优先级文本
     getPriorityText(priority) {
       const priorityMap = {
         '1': '高',
         '2': '中',
         '3': '低'
       }
       return priorityMap[priority] || priority
     }
  }
}
</script>

<style scoped>
.pm-worklog-view {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2d3a4b;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-row {
  align-items: end;
}

.filter-row .el-form-item {
  margin-bottom: 0;
}

.filter-row .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.summary-cards {
  margin-bottom: 20px;
}

.summary-card {
  height: 100px;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
}

.summary-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 10px 0;
}

.card-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: #fff;
}

.card-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.overtime {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.members {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  color: #2d3a4b;
  line-height: 1;
}

.card-value .unit {
  font-size: 14px;
  color: #909399;
  margin-left: 4px;
}

.tabs-card {
  margin-bottom: 20px;
}

.statistics-tabs .el-tabs__header {
  margin-bottom: 20px;
}

.statistics-tabs .el-tabs__item {
  font-size: 16px;
  font-weight: 500;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-empty {
  margin: 60px 0;
}

/* 状态标签样式继承父组件 */

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
  }
  
  .filter-row .el-col {
    width: 100%;
    margin-bottom: 15px;
  }
  
  .summary-cards .el-col {
    margin-bottom: 15px;
  }
  
  .card-value {
    font-size: 24px;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .statistics-tabs .el-tabs__item {
    font-size: 14px;
  }
}
</style>
